<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="溯源类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag type="radio"  v-decorator="['commodityType', validatorRules.commodityType]" :trigger-change="true" dictCode="commodity_type" placeholder="请选择溯源类型" :disabled="model.commodityStatus==1"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="商品名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :maxLength="10" v-decorator="['commodityName', validatorRules.commodityName]" placeholder="请输入商品名称(10个字以内)"  ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="商品图片" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <span style="color: #ff0000">(图片尺寸:1:1 图片大小：＜1M)</span>
              <j-image-upload isMultiple :number="1" bizPath="commodity/commodity"  v-decorator="['commodityImg', validatorRules.commodityImg]" ></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24"  align="center" >
            <a-button class="new-btn" type="dashed" @click="addNewBute">
              <a-icon type="plus"/>
              添加新参数
            </a-button>
          </a-col>
          <a-col :span="24"  align="center">
              <div v-for="(item,index) in buteList" :key="index"  style="margin-top: 10px;">
                  <a-input v-model="item.attributeName"   :maxLength="6" placeholder="属性名称" @blur="checkInput" style="width: 30%; margin-right: 8px"/>
                  <a-input v-model="item.attributeValue"  :maxLength="6" placeholder="最多可输入6个字" @blur="checkInput" style="width: 30%; margin-right: 8px"/>
                  <a-icon class="dynamic-delete-button" type="minus-circle-o" @click="removeFilterParams(item,index)"/>
              </div>
               <div class="ant-form-explain" style="color: #ff0000;">{{buteRule}}</div>
          </a-col>
<!--          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>-->
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import { validateDuplicateValue } from '@/utils/util'

  export default {
    name: 'QyCommodityForm',
    components: {

    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          commodityType: {
            rules: [
              { required: true, message: '请输入溯源类型!'},
            ]
          },
          commodityName: {
            rules: [
              { required: true, message: '请输入商品名称!'},
            ]
          },
          commodityImg: {
            rules: [
              { required: true, message: '请上传商品图片!'},
            ]
          },
          attributeName:{
            rules: [
              { required: true, message: '请输入属性名称!'},
            ]
          },
          attributeValue:{
            rules: [
              { required: true, message: '请输入属性值!'},
            ]
          }
        },
        url: {
          add: "/qy/qyCommodity/add",
          edit: "/qy/qyCommodity/edit",
          queryById: "/qy/qyCommodity/queryById"
        },buteList:[
          {"attributeName":"产地"},
          {"attributeName":"配料"},
          {"attributeName":"储存方式"},
          {"attributeName":"保质期"}
        ],
        buteRule:"",
        isBute:false
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      add () {
        this.showAddData();
      },
      edit (record) {
        this.form.resetFields();
        //this.model = Object.assign({}, record);
        this.model = JSON.parse(JSON.stringify(record));

        if(this.model.commodityAttributeList){
          this.buteList = this.model.commodityAttributeList;
        }
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model,'createBy','createTime','updateBy','updateTime','companyId','commodityType','commodityName','commodityImg','oneCodeNum','oneCodeTotalNum','muchCodeNum','muchCodeTotalNum'));
        })

      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },//新增的时候检查是否有未完成的
      showAddData(){
          getAction(this.url.queryById,{}).then((res)=>{
            if(res.success){
              if(res.result){
                this.edit(res.result);
                this.$emit("initRecord",res.result);
              }else{

                this.edit({
                  commodityAttributeList:[
                    {"attributeName":"产地"},
                    {"attributeName":"配料"},
                    {"attributeName":"储存方式"},
                    {"attributeName":"保质期"}
                  ],
                  commodityType:1
                });
              }

            }
          });
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.checkInput();
            if(that.isBute){
              that.$emit("changeLoading",true);
              that.model.commodityAttributeList = that.buteList;
              that.confirmLoading = true;
              let httpurl = '';
              let method = '';
              if(!this.model.id){
                httpurl+=this.url.add;
                method = 'post';
              }else{
                httpurl+=this.url.edit;
                method = 'put';
              }
              let formData = Object.assign(this.model, values);
              httpAction(httpurl,formData,method).then((res)=>{
                if(res.success){
                  that.$message.success(res.message);
                  that.$parent.commodityId = res.result;
                  that.$emit("changeNext",res.result);
                }else{
                  that.$message.warning(res.message);
                }
                that.$emit("changeLoading",false);
              }).finally(function(){
                that.confirmLoading = false;
              });
            }

          }

        })
      },
      popupCallback(row){
        this.form.setFieldsValue(pick(row,'createBy','createTime','updateBy','updateTime','companyId','commodityType','commodityName','commodityImg','oneCodeNum','oneCodeTotalNum','muchCodeNum','muchCodeTotalNum','commodityAttributeList'))
      },
      removeFilterParams(item,idx){//删除属性
        if(this.model.commodityAttributeList.length>0){
          this.model.commodityAttributeList.splice(idx,1);
        }
      },
      addNewBute(){//添加一个新的属性
        this.model.commodityAttributeList.push({});
      },checkInput(){
        if(this.buteList.length>0){
          for(var k in this.buteList){
            if(!this.buteList[k].attributeName){
               this.buteRule = "请输入属性名称!";
               this.isBute = false;
              return;
            }
            if(!this.buteList[k].attributeValue){
              this.buteRule = "请输入属性值!";
              this.isBute = false;
              return;
            }
          }
          this.buteRule = "";
          this.isBute = true;
        }else{
          this.isBute = false;
        }

      }
    }
  }
</script>